import express from 'express';
import { dbPool } from '../config/database.js';

const router = express.Router();

// 获取评论列表
router.get('/comments', async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 20, 
      status, 
      articleId, 
      featured 
    } = req.query;

    const offset = (page - 1) * limit;
    
    // 构建查询条件
    let whereClause = 'WHERE 1=1';
    const params = [];
    
    if (status) {
      params.push(status);
      whereClause += ` AND c.status = $${params.length}`;
    }
    
    if (articleId) {
      params.push(parseInt(articleId));
      whereClause += ` AND c.article_id = $${params.length}`;
    }
    
    if (featured === 'true') {
      whereClause += ` AND c.is_featured = true`;
    }

    // 获取评论总数
    const countQuery = `
      SELECT COUNT(*) as total 
      FROM comments c 
      ${whereClause}
    `;
    const countResult = await dbPool.query(countQuery, params);
    const total = parseInt(countResult.rows[0].total);

    // 获取评论列表
    const query = `
      SELECT 
        c.id, c.article_id, c.parent_id, c.author_name, c.author_email, 
        c.content, c.status, c.is_featured, c.ip_address, c.user_agent,
        c.created_at, c.updated_at,
        a.title as article_title, a.slug as article_slug,
        p.author_name as parent_author_name, p.content as parent_content
      FROM comments c
      LEFT JOIN articles a ON c.article_id = a.id
      LEFT JOIN comments p ON c.parent_id = p.id
      ${whereClause}
      ORDER BY c.created_at DESC
      LIMIT $${params.length + 1} OFFSET $${params.length + 2}
    `;
    
    const queryParams = [...params, parseInt(limit), parseInt(offset)];
    const result = await dbPool.query(query, queryParams);

    // 格式化评论数据
    const comments = result.rows.map(row => ({
      id: row.id,
      articleId: row.article_id,
      parentId: row.parent_id,
      authorName: row.author_name,
      authorEmail: row.author_email,
      content: row.content,
      status: row.status,
      isFeatured: row.is_featured,
      ipAddress: row.ip_address,
      userAgent: row.user_agent,
      createdAt: row.created_at,
      updatedAt: row.updated_at,
      article: row.article_title ? {
        id: row.article_id,
        title: row.article_title,
        slug: row.article_slug
      } : null,
      parent: row.parent_author_name ? {
        id: row.parent_id,
        authorName: row.parent_author_name,
        content: row.parent_content
      } : null
    }));

    res.json({
      success: true,
      data: {
        comments,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total: total,
          pages: Math.ceil(total / limit)
        }
      }
    });
  } catch (error) {
    console.error('获取评论列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取评论列表失败'
    });
  }
});

  // 获取单个评论
  router.get('/comments/:id', async (req, res) => {
    try {
      const commentId = parseInt(req.params.id);
      
      const query = `
        SELECT 
          c.id, c.article_id, c.parent_id, c.author_name, c.author_email, 
          c.content, c.status, c.is_featured, c.ip_address, c.user_agent,
          c.created_at, c.updated_at,
          a.title as article_title, a.slug as article_slug,
          p.author_name as parent_author_name, p.content as parent_content
        FROM comments c
        LEFT JOIN articles a ON c.article_id = a.id
        LEFT JOIN comments p ON c.parent_id = p.id
        WHERE c.id = $1
      `;
      
      const result = await dbPool.query(query, [commentId]);
      
      if (result.rows.length === 0) {
        return res.status(404).json({
          success: false,
          message: '评论不存在'
        });
      }

      const comment = result.rows[0];
      
      // 获取回复列表
      const repliesQuery = `
        SELECT 
          r.id, r.article_id, r.author_name, r.author_email, r.content,
          r.status, r.is_featured, r.created_at, r.updated_at,
          a.title as article_title
        FROM comments r
        LEFT JOIN articles a ON r.article_id = a.id
        WHERE r.parent_id = $1
        ORDER BY r.created_at ASC
      `;
      
      const repliesResult = await dbPool.query(repliesQuery, [commentId]);
      
      const formattedComment = {
        id: comment.id,
        articleId: comment.article_id,
        parentId: comment.parent_id,
        authorName: comment.author_name,
        authorEmail: comment.author_email,
        content: comment.content,
        status: comment.status,
        isFeatured: comment.is_featured,
        ipAddress: comment.ip_address,
        userAgent: comment.user_agent,
        createdAt: comment.created_at,
        updatedAt: comment.updated_at,
        article: comment.article_title ? {
          id: comment.article_id,
          title: comment.article_title,
          slug: comment.article_slug
        } : null,
        parent: comment.parent_author_name ? {
          id: comment.parent_id,
          authorName: comment.parent_author_name,
          content: comment.parent_content
        } : null,
        replies: repliesResult.rows.map(reply => ({
          id: reply.id,
          articleId: reply.article_id,
          authorName: reply.author_name,
          authorEmail: reply.author_email,
          content: reply.content,
          status: reply.status,
          isFeatured: reply.is_featured,
          createdAt: reply.created_at,
          updatedAt: reply.updated_at,
          article: reply.article_title ? {
            id: reply.article_id,
            title: reply.article_title
          } : null
        }))
      };

      res.json({
        success: true,
        data: formattedComment
      });
    } catch (error) {
      console.error('获取评论失败:', error);
      res.status(500).json({
        success: false,
        message: '获取评论失败'
      });
    }
  });

  // 回复评论
  router.post('/comments/:id/reply', async (req, res) => {
    try {
      const parentId = parseInt(req.params.id);
      
      // 检查父评论是否存在
      const parentCheck = await dbPool.query(
        'SELECT id, article_id FROM comments WHERE id = $1', 
        [parentId]
      );
      
      if (parentCheck.rows.length === 0) {
        return res.status(404).json({
          success: false,
          message: '父评论不存在'
        });
      }

      const { authorName, authorEmail, content } = req.body;

      if (!authorName || !authorEmail || !content) {
        return res.status(400).json({
          success: false,
          message: '作者名称、邮箱和内容不能为空'
        });
      }

      // 插入回复评论
      const insertQuery = `
        INSERT INTO comments (
          article_id, parent_id, author_name, author_email, content, 
          status, is_featured, ip_address, user_agent, created_at, updated_at
        ) VALUES ($1, $2, $3, $4, $5, 'approved', false, $6, $7, NOW(), NOW())
        RETURNING *
      `;
      
      const result = await dbPool.query(insertQuery, [
        parentCheck.rows[0].article_id,
        parentId,
        authorName,
        authorEmail,
        content,
        req.ip,
        req.get('User-Agent')
      ]);

      const reply = result.rows[0];
      
      // 格式化返回数据
      const formattedReply = {
        id: reply.id,
        articleId: reply.article_id,
        parentId: reply.parent_id,
        authorName: reply.author_name,
        authorEmail: reply.author_email,
        content: reply.content,
        status: reply.status,
        isFeatured: reply.is_featured,
        ipAddress: reply.ip_address,
        userAgent: reply.user_agent,
        createdAt: reply.created_at,
        updatedAt: reply.updated_at
      };

      res.json({
        success: true,
        data: formattedReply,
        message: '回复成功'
      });
    } catch (error) {
      console.error('回复评论失败:', error);
      res.status(500).json({
        success: false,
        message: '回复评论失败'
      });
    }
  });

  // 更新评论状态
  router.put('/comments/:id/status', async (req, res) => {
    try {
      const commentId = parseInt(req.params.id);
      const { status } = req.body;
      
      if (!['pending', 'approved', 'rejected', 'featured'].includes(status)) {
        return res.status(400).json({
          success: false,
          message: '状态值无效'
        });
      }

      // 检查评论是否存在
      const checkResult = await dbPool.query(
        'SELECT id FROM comments WHERE id = $1', 
        [commentId]
      );
      
      if (checkResult.rows.length === 0) {
        return res.status(404).json({
          success: false,
          message: '评论不存在'
        });
      }

      // 更新评论状态
      const updateQuery = `
        UPDATE comments 
        SET status = $1, is_featured = $2, updated_at = NOW()
        WHERE id = $3
        RETURNING *
      `;
      
      const result = await dbPool.query(updateQuery, [
        status,
        status === 'featured',
        commentId
      ]);

      const updatedComment = result.rows[0];
      
      // 格式化返回数据
      const formattedComment = {
        id: updatedComment.id,
        articleId: updatedComment.article_id,
        parentId: updatedComment.parent_id,
        authorName: updatedComment.author_name,
        authorEmail: updatedComment.author_email,
        content: updatedComment.content,
        status: updatedComment.status,
        isFeatured: updatedComment.is_featured,
        ipAddress: updatedComment.ip_address,
        userAgent: updatedComment.user_agent,
        createdAt: updatedComment.created_at,
        updatedAt: updatedComment.updated_at
      };

      res.json({
        success: true,
        data: formattedComment,
        message: '状态更新成功'
      });
    } catch (error) {
      console.error('更新评论状态失败:', error);
      res.status(500).json({
        success: false,
        message: '更新评论状态失败'
      });
    }
  });

  // 设置/取消精选
  router.put('/comments/:id/featured', async (req, res) => {
    try {
      const commentId = parseInt(req.params.id);
      const { featured } = req.body;
      
      // 检查评论是否存在
      const checkResult = await dbPool.query(
        'SELECT id FROM comments WHERE id = $1', 
        [commentId]
      );
      
      if (checkResult.rows.length === 0) {
        return res.status(404).json({
          success: false,
          message: '评论不存在'
        });
      }

      // 更新评论精选状态
      const updateQuery = `
        UPDATE comments 
        SET is_featured = $1, status = $2, updated_at = NOW()
        WHERE id = $3
        RETURNING *
      `;
      
      const result = await dbPool.query(updateQuery, [
        featured,
        featured ? 'featured' : 'approved',
        commentId
      ]);

      const updatedComment = result.rows[0];
      
      // 格式化返回数据
      const formattedComment = {
        id: updatedComment.id,
        articleId: updatedComment.article_id,
        parentId: updatedComment.parent_id,
        authorName: updatedComment.author_name,
        authorEmail: updatedComment.author_email,
        content: updatedComment.content,
        status: updatedComment.status,
        isFeatured: updatedComment.is_featured,
        ipAddress: updatedComment.ip_address,
        userAgent: updatedComment.user_agent,
        createdAt: updatedComment.created_at,
        updatedAt: updatedComment.updated_at
      };

      res.json({
        success: true,
        data: formattedComment,
        message: featured ? '已设为精选' : '已取消精选'
      });
    } catch (error) {
      console.error('设置精选失败:', error);
      res.status(500).json({
        success: false,
        message: '设置精选失败'
      });
    }
  });

  // 删除评论
  router.delete('/comments/:id', async (req, res) => {
    try {
      const commentId = parseInt(req.params.id);
      
      // 检查评论是否存在
      const checkResult = await dbPool.query(
        'SELECT id FROM comments WHERE id = $1', 
        [commentId]
      );
      
      if (checkResult.rows.length === 0) {
        return res.status(404).json({
          success: false,
          message: '评论不存在'
        });
      }

      // 检查是否有回复，如果有则不能删除
      const replyCountResult = await dbPool.query(
        'SELECT COUNT(*) as count FROM comments WHERE parent_id = $1', 
        [commentId]
      );
      
      const replyCount = parseInt(replyCountResult.rows[0].count);

      if (replyCount > 0) {
        return res.status(400).json({
          success: false,
          message: '该评论有回复，无法删除'
        });
      }

      // 删除评论
      await dbPool.query('DELETE FROM comments WHERE id = $1', [commentId]);

      res.json({
        success: true,
        message: '评论删除成功'
      });
    } catch (error) {
      console.error('删除评论失败:', error);
      res.status(500).json({
        success: false,
        message: '删除评论失败'
      });
    }
  });

  // 批量操作
  router.post('/comments/batch', async (req, res) => {
    try {
      const { ids, action } = req.body;
      
      if (!Array.isArray(ids) || ids.length === 0) {
        return res.status(400).json({
          success: false,
          message: '请选择要操作的评论'
        });
      }

      let updatedCount = 0;
      
      switch (action) {
        case 'approve':
          const approveResult = await dbPool.query(
            `UPDATE comments 
             SET status = 'approved', is_featured = false, updated_at = NOW()
             WHERE id = ANY($1) AND status = 'pending'
             RETURNING id`,
            [ids]
          );
          updatedCount = approveResult.rowCount;
          break;
          
        case 'reject':
          const rejectResult = await dbPool.query(
            `UPDATE comments 
             SET status = 'rejected', is_featured = false, updated_at = NOW()
             WHERE id = ANY($1) AND status = 'pending'
             RETURNING id`,
            [ids]
          );
          updatedCount = rejectResult.rowCount;
          break;
          
        case 'feature':
          const featureResult = await dbPool.query(
            `UPDATE comments 
             SET status = 'featured', is_featured = true, updated_at = NOW()
             WHERE id = ANY($1) AND status = 'approved'
             RETURNING id`,
            [ids]
          );
          updatedCount = featureResult.rowCount;
          break;
          
        case 'unfeature':
          const unfeatureResult = await dbPool.query(
            `UPDATE comments 
             SET status = 'approved', is_featured = false, updated_at = NOW()
             WHERE id = ANY($1) AND status = 'featured'
             RETURNING id`,
            [ids]
          );
          updatedCount = unfeatureResult.rowCount;
          break;
          
        case 'delete':
          // 检查是否有回复
          const replyCheckQuery = `
            SELECT c.id, COUNT(r.id) as reply_count
            FROM comments c
            LEFT JOIN comments r ON c.id = r.parent_id
            WHERE c.id = ANY($1)
            GROUP BY c.id
          `;
          
          const replyCheckResult = await dbPool.query(replyCheckQuery, [ids]);
          
          const deletableIds = replyCheckResult.rows
            .filter(row => parseInt(row.reply_count) === 0)
            .map(row => row.id);

          if (deletableIds.length === 0) {
            return res.status(400).json({
              success: false,
              message: '选中的评论都有回复，无法删除'
            });
          }

          const deleteResult = await dbPool.query(
            'DELETE FROM comments WHERE id = ANY($1) RETURNING id',
            [deletableIds]
          );
          updatedCount = deleteResult.rowCount;
          break;
          
        default:
          return res.status(400).json({
            success: false,
            message: '操作类型无效'
          });
      }

      res.json({
        success: true,
        data: { updatedCount },
        message: `批量操作成功，影响 ${updatedCount} 条评论`
      });
    } catch (error) {
      console.error('批量操作失败:', error);
      res.status(500).json({
        success: false,
        message: '批量操作失败'
      });
    }
  });

  export default router;